package com.home.security.app.interceptor;

import com.home.base.core.constants.UserInfoConstant;
import com.home.base.core.context.BaseContextHandler;
import com.home.base.core.framework.enums.ResultCodeEnum;
import com.home.common.utils.json.JsonUtils;
import com.home.common.utils.string.StringUtils;
import com.home.security.app.JwtTokenUtil;
import com.home.security.app.constants.AppAuthConstant;
import com.home.security.app.exception.ClientTokenException;
import com.home.security.app.token.IJWTInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Description: 拦截器
 * Created by 王大宸 on 2020-12-11 15:51
 * Created with IntelliJ IDEA.
 */
public class SecurityAppAuthInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(SecurityAppAuthInterceptor.class);
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        try {
            String token = request.getHeader(AppAuthConstant.JWT_KEY_AUTHENTICATION);
            if (StringUtils.isEmpty(token)) {
                if (request.getCookies() != null) {
                    for (Cookie cookie : request.getCookies()) {
                        if (cookie.getName().equals(AppAuthConstant.JWT_KEY_AUTHENTICATION)) {
                            token = cookie.getValue();
                        }
                    }
                }
            }
            if (StringUtils.isEmpty(token)) {
                throw new ClientTokenException("获取当前登录用户失败");
            }

            token = token.replaceAll("%20", " ");
            if (token.startsWith(AppAuthConstant.JWT_KEY_TOKEN_TYPE)) {
                token = token.substring(AppAuthConstant.JWT_KEY_TOKEN_TYPE.length());
            }

            IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromToken(token);

            BaseContextHandler.setAccount(infoFromToken.getUniqueName());
            BaseContextHandler.setName(infoFromToken.getName());
            BaseContextHandler.setUserId(infoFromToken.getId());
            BaseContextHandler.setAvatar(infoFromToken.getOtherInfo().get(UserInfoConstant.AVATAR));
            BaseContextHandler.setUserType(infoFromToken.getOtherInfo().get(UserInfoConstant.USER_TYPE));
            return super.preHandle(request, response, handler);
        } catch (Exception e) {
            logger.info("用户认证错误：", e);
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(getMessage(ResultCodeEnum.CLIENT_TOKEN_EXCEPTION.getStatus(), e.getMessage()));
            return false;

        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private String getMessage(int status, String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", status);
        map.put("msg", msg);
        map.put("data", null);
        map.put("success", false);
        return JsonUtils.toJson(map);
    }
}
